#define _CRT_SECURE_NO_WARNINGS


#include"SeqList.h"



void SeqListInit(SL* pa)
{
	assert(pa != NULL);

	pa->a = NULL;
	pa->capacity = pa->size = 0;

}



void SeqListDestory(SL* pa)
{
	assert(pa != NULL);

	if (pa->size)
	{
		free(pa->a);
		pa->a = NULL;
		pa->capacity = pa->size = 0;
	}
}



void SeqCheckCapacity(SL* pb)
{
	assert(pb != NULL);
	
	if (pb->capacity == pb->size)
	{

		SLDataType* pf = (SLDataType*)realloc(pb->a, (pb->capacity + 2) * sizeof(SLDataType));
		if (pf == NULL)
		{
			perror("realloc fail\n");
			return;
		}
		pb->a = pf;
		pb->capacity += 2;
	}
}



void SeqListPushBack(SL* pc, SLDataType x)
{
	/*assert(pc != NULL);

		SeqCheckCapacity(pc);
		pc->a[pc->size] = x;
		pc->size++;*/

	SeqListInsert(pc, pc->size, x);
}



void SeqListPopBack(SL* pd)
{
	/*assert(pd != NULL);

	if (pd->size)
	{
		pd->size--;
	}*/

	SeqListErase(pd, pd->size);
}



void SeqListPushFront(SL* pe, SLDataType x)
{
	/*assert(pe != NULL);

	SeqCheckCapacity(pe);
	int i = 0;
	for (i = pe->size; i >0; i--)
	{
		pe->a[i + 1] = pe->a[i];
	}

	pe->a[i] = x;
	pe->size++;*/

	SeqListInsert(pe, 0, x);
}



void SeqListPopFront(SL* pf)
{
	/*assert(pf != NULL);

	int i = 0;
	for (i = 0; i < pf->size-1; i++)
	{
		pf->a[i] = pf->a[i + 1];
	}
	pf->size--;*/

	SeqListErase(pf, 0);
}



void SeqListInsert(SL* pg,int pos, SLDataType x)
{
	assert(pg != NULL);
	assert(pos <= pg->size && pos >= 0);

		SeqCheckCapacity(pg);

		int end = pg->size - 1;
		while (end>=pos)
		{
			pg->a[end + 1] = pg->a[end];
			end--;
		}

		pg->a[pos] = x;
		pg->size++;

}



void SeqListErase(SL* ph, int pos)
{
	assert(ph != NULL);
	assert(pos <= ph->size && pos >= 0);

	int i = 0;
	for (i = pos; i < ph->size-1; i++)
	{
		ph->a[i] = ph->a[i + 1];
	}

	ph->size--;

}



void SeqListPrint(SL* pa)
{
	assert(pa != NULL);

	int i = 0;
	for (i = 0; i < pa->size; i++)
	{
		printf("%d ", pa->a[i]);
	}
	putchar('\n');

}



void SeqListModify(SL* pi, int pos, SLDataType x)
{
	assert(pi != NULL);
	assert(pos <= pi->size && pos >= 0);

	pi->a[pos] = x;

}



int SeqListFind(SL* ps,SLDataType x)
{
	assert(ps != NULL);

	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
			return i;
	}

	return -1;
}